<?php
namespace Frieza\Modules\Decoration\Controllers;

use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use App\Admin\Extensions\Tools\UserButton;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Doraemon\model\Category;
use Doraemon\service\Decoration\Main as sMain;
use Doraemon\model\Decoration\Adv as mAdv;
use Doraemon\model\Decoration\Subject as mSubject;
use Doraemon\model\Decoration\Tag as mTag;
use Doraemon\service\Decoration\Cache as sCache;
use Doraemon\model\Decoration\Category as mCategory;
use Doraemon\service\es\EsDecorateTopic;
use Doraemon\cache\DecorateThemeCount;

class SubjectController extends Controller
{
    const PAGE_SIZE = 500;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    private function _filterWhere($params){
        if(isset($params['_columns_'])){
            unset($params['_columns_']);
        }
        if(isset($params['_pjax'])){
            unset($params['_pjax']);
        }

        $data = [];
        $page = isset($params['page']) ? $params['page'] : 1;
        $pageSize = isset($params['per_page']) ? $params['per_page'] : self::PAGE_SIZE;
        $limit = [($page - 1) * $pageSize, $pageSize];
        unset($params['page']);

        $where = [];
        foreach ($params as $_k => &$_v) {
            if ($_v <> '') {
                $where[$_k] = $_v;
                if($_k == 'date_time') {
                    if ($where[$_k]['start'] <> '') {
                        $where['start_time[>=]'] = $where[$_k]['start'];
                        unset($where[$_k]['start']);
                    }
                    if ($where[$_k]['end'] <> '') {
                        $where['end_time[<]'] = $where[$_k]['end'];
                        $where[$_k]['end'];
                    }
                    unset($where[$_k]);
                }
            }
        }

        $data = [
            'LIMIT' => $limit,
        ];

        if (!empty($where)) {
            $data['AND'] = $where;
        }

        return $data;
    }

    public function list(Request $request,Content $content, $parentId = 0, $sonId = 0){
        $request = $request->all();
        $preUrl = '';
        if($parentId > 0){
            $request['parent_id'] = $parentId;
            $preUrl = '/decoration/category/'.$parentId.'/edit';
        }
        if($sonId > 0){
            $request['id'] = $sonId;
            $preUrl = $preUrl. '/' .$sonId.'/edit';
        }
        if(!empty($preUrl)){
            $preUrl = ['text' => '上级分类', 'url' => $preUrl];
        }
        $request = self::_filterWhere($request);

        if(!empty($preUrl)) {
            return $content
                ->header('主题列表')
                ->breadcrumb(
                    $preUrl,
                    ['text' => '主题列表']
                )
                ->body(self::listAction($request));
        }else{
            return $content
                ->header('主题列表')
                ->breadcrumb(
                    ['text' => '主题列表']
                )
                ->body(self::listAction($request));
        }
    }

    public function listAction($request = []){
        $data = [
            'list'=> [],
            'total' => 0,
        ];
        if($request['AND']['id'] > 0){
            $sql = 'select id,sid from `hhz_decoration_adv` where FIND_IN_SET('.$request['AND']['id'].',rela_id) and show_type = '.mAdv::SHOW_TYPE_1;
            $advId = mAdv::query($sql)->fetchAll();
            if(!empty($advId)){
                $sid =  array_column($advId, 'sid');
                if(isset($request['AND']['name'])) {
                    $data = sMain::getSubject(['id' => $sid, 'name[~]'=>$request['AND']['name']]);
                }else{
                    $data = sMain::getSubject(['id' => $sid]);
                }
            }
        }else{
            $data = sMain::getSubject($request);
        }

        $gridModel = new pGridDataModel($data['list'], $data['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid)use($request) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('name', '主题名称')->placeholder('请输入主题名称');
                });
            });

            $grid->tools(function (Grid\Tools $tool)use($request) {
                $tool->append(new UserButton(UserButton::TYPE_HREF, '', '主题位排序', '',
                    '/admin/decoration/subject/sorts/'.$request['AND']['parent_id'].'/'.$request['AND']['id']));
            });

            $grid->column('id', 'id');
            $grid->column('name', '主题名称');
            $grid->column('color', '背景颜色')->display(function(){
                return '<p style="background-color: '.$this->color.';color:'.$this->color.';width: 50px; display: block">颜色</p>';
            });
            $grid->column('rela_tag', '关联tag');
            $grid->column('rela_wiki', '关联wiki分类');
            $grid->column('search_tag', '搜索描述');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '编辑时间');

        });

        $list = $listGrid->render();

        return $list;
    }

    public function edit(Request $request,Content $content, $parentId = 0, $sonId = 0, $sid = 0){
        $requests = $request->all();
        $requests['parent_id'] = $parentId;
        $requests['id'] = $sonId;
        $requests['sid'] = $sid;
        $requests = self::_filterWhere($requests);

        if($parentId > 0){
            $request['parent_id'] = $parentId;
            $preUrl = '/decoration/category/'.$parentId.'/edit';
        }
        if($sonId > 0){
            $request['id'] = $sonId;
            $preUrl = $preUrl. '/' .$sonId.'/edit';
        }

        $tab = new Tab();
        $tab->add('基本信息', self::editAction(
            $requests,
            strpos($request->url(), 'create'),
            '/admin'.$preUrl.'/subject/'.$sid.'/save')
        );
        if(!strpos($request->url(), 'create')) {
            $tab->addLink('资源位列表', '/admin/decoration/category/'.$parentId.'/edit/'.$sonId.'/edit/subject/'.$sid.'/adv');
        }

        if(!empty($preUrl)){
            $preUrls = ['text' => '上级分类', 'url' => $preUrl];
        }

        return $content
            ->header('分类编辑')
            ->breadcrumb(
                $preUrls,
                ['text' => '主题列表', 'url' => $preUrl.'/subject'],
                ['text' => '编辑主题', 'url' => '/decoration/category/create']
            )
            ->body($tab);
    }

    public function editAction($request, $isCreate = false, $preUrl = ''){
        $data = [];
        if(!$isCreate) {
            if (!empty($request['AND']['sid'])) {
                $data = mSubject::getOneByWhere(['id' => $request['AND']['sid']]);
            }
        }

        $form = new Form($data);

        if(isset($request['AND']['sid'])){
            $form->hidden('id');
        }

        $form->text('name', '主题名称')->setWidth(4, 2)->required('不能为空');
        $form->color('color', '主题背景色')->setWidth(4, 2)->required('不能为空');
        $form->text('rela_tag', '关联tag');
        $form->multipleSelect('rela_wiki', '关联wiki分类')->options(Category::getCategorysByDeep([1,2,3]));
//        $form->checkbox('rela_wiki2', '关联wiki分类') ->options($wiki_category);
        $form->text('search_tag', '搜索描述')->setWidth(4, 2);

        $form->action($preUrl);

        return $form->render();
    }

    public static function save(Request $request, $parentId = 0, $sonId = 0, $sid = 0)
    {
        $params = $request->all();
        if(!empty($params['rela_wiki'])){
            $params['rela_wiki'] = implode(',', array_filter($params['rela_wiki']));
        }

        $param = [
            'name'=> $params['name'],
            'color'=> $params['color'],
            'rela_tag'=> $params['rela_tag'],
            'rela_wiki'=> $params['rela_wiki'],
            'search_tag'=> $params['search_tag'],
            'admin_id'=>Admin::user()->id,
        ];

        if(!isset($params['id'])) {
            $param['add_time'] = date('Y-m-d H:i:s');
            $result = mSubject::addData($param);
            $param['id'] = $result;
        }else{
            $result = mSubject::updateData($param,['id'=>$params['id']]);
            $param['id'] = $params['id'];
        }

        if($result){
            sCache::updateCache();

            //更新搜索的缓存信息
            \Doraemon\cache\Queue::insertQueue('queue/decoratetopic/save', array(
                'id' => $param['id'],
            ), \Doraemon\cache\Queue::QUEUE_DORAEMON);
//            $DecorateThemeCount = DecorateThemeCount::getOne($param['id']);
//            $data = array(
//                "name" => trim($param["name"]),
//                "related_tag" => str_replace('，', ',', trim($param["rela_tag"])),
//                "addtime" => isset($param["add_time"])?strtotime($param["add_time"]) : 0,
//                "edittime" => time(),
//                "uv" => isset($DecorateThemeCount["uv"])
//            );
//             EsDecorateTopic::post($param['id'], $data);

            $success = new MessageBag([
                'title' => '操作成功'
            ]);
            if($sid) {
                return redirect('/admin/decoration/category/' . $parentId . '/edit/' . $sonId . '/edit/subject/' . $sid . '/edit')->with(compact('success'));
            }else{
                return redirect('/admin/decoration/subject/create')->with(compact('success'));
            }
        }else{
            $error = new MessageBag([
                'title' => $result
            ]);

            return back()->with(compact('error'));
        }

    }

    public static function del($id,  $parentId = 0, $sonId = 0, $sid = 0)
    {
        //如果关联了关键词或者广告位，提示不能删除
        //$sql = 'select id from `hhz_decoration_tag` where FIND_IN_SET('.$sid.',sid)';
        //$rela_tag = mTag::query($sql)->fetchAll();
        $rela_adv = mAdv::getAllByWhere(['sid'=>$sid],'id');
        if(!empty($rela_adv)){
            return response()->json([
                'status' => false,
                'message' => "已关联关键词或者广告位，不能删除，请先解除关联",
            ]);
        }


        $data = ['status'=>mSubject::STATUS_DELETE];
        $result = mSubject::updateData($data, ['id'=>$sid]);

        if($result){
            sCache::updateCache();

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public static function delete($id)
    {
        $data = mAdv::getOneByWhere(['id'=>$id]);
        //如果关联了关键词或者广告位，提示不能删除
        //$sql = 'select id from `hhz_decoration_tag` where FIND_IN_SET('.$data['sid'].',sid)';
        //$rela_tag = mTag::query($sql)->fetchAll();
        $rela_adv = mAdv::getAllByWhere(['sid'=>$id],'id');
        if(!empty($rela_adv)){
            return response()->json([
                'status' => false,
                'message' => "已关联关键词或者广告位，不能删除，请先解除关联",
            ]);
        }


        $data = ['status'=>mSubject::STATUS_DELETE];
        $result = mSubject::updateData($data, ['id'=>$id]);

        if($result){
            sCache::updateCache();

            //删除搜索主题的缓存
            \Doraemon\cache\Queue::insertQueue('queue/decoratetopic/delete', array(
                'id' => $id,
            ), \Doraemon\cache\Queue::QUEUE_DORAEMON);
//            EsDecorateTopic::delete($id);

            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }


    public function create(Request $request,Content $content, $id = 0){
        $request = $request->all();
        if($id>0){
            $request['id'] = $id;
        }
        $request = self::_filterWhere($request);

        $tab = new Tab();
        $tab->add('主题列表', self::listGrid($request));
        if($id>0) {
            $tab->add('编辑主题', self::createForm($request), true);
        }else{
            $tab->add('创建主题', self::createForm($request));
        }

        if(!empty($preUrl)) {
            return $content
                ->header('创建主题')
                ->breadcrumb(
                    $preUrl,
                    ['text' => '创建主题']
                )
                ->body($tab);
        }else{
            return $content
                ->header('创建主题')
                ->breadcrumb(
                    ['text' => '主题列表', 'url' => '/decoration/subject/create'],
                    ['text' => '创建主题']
                )
                ->body($tab);
        }
    }

    public function listGrid($request = []){
        $subject = sMain::getSubject($request);
        $gridModel = new pGridDataModel($subject['list'], $subject['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            //$grid->disableFilter();
            //$grid->disableTools();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('name', '主题名称')->placeholder('请输入主题名称');
                });
            });

            $grid->column('id', 'id');
            $grid->column('name', '主题名称');
            $grid->column('color', '背景颜色')->display(function(){
                return '<p style="background-color: '.$this->color.';color:'.$this->color.';width: 50px; display: block">颜色</p>';
            });
            $grid->column('rela_tag', '关联tag');
            $grid->column('rela_wiki', '关联wiki分类');
            $grid->column('search_tag', '搜索描述');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '编辑时间');
            $grid->column('adv', '资源位')->display(function(){
                return '<a class="grid-row-edit" href="/admin/decoration/subject/'.$this->id.'/adv"><i class="fa fa-map">资源位</i></a>';
            });

        });

        $list = $listGrid->render();

        return $list;
    }

    public function createForm($request){

        if(!empty($request['AND']['id'])){
            $data = mSubject::getOneByWhere(['id'=>$request['AND']['id']]);
        }else{
            $data = [];
        }
        $form = new Form($data);

        if(isset($request['AND']['id'])){
            $form->hidden('id');
        }

        $form->text('name', '主题名称')->setWidth(4, 2)->required('不能为空');
        $form->color('color', '主题背景色')->setWidth(4, 2)->required('不能为空');
        $form->text('rela_tag', '关联tag');
        $form->multipleSelect('rela_wiki', '关联wiki分类')->options(Category::getCategorysByDeep([1,2,3]));
//        $form->checkbox('rela_wiki2', '关联wiki分类') ->options($wiki_category);
        $form->text('search_tag', '搜索描述')->setWidth(4, 2);

        $form->action('/admin/decoration/subject/save');

        return $form->render();
    }

    public function sort(Request $request){
        $params = $request->all();

        $result = mAdv::action(function()use($params){
            foreach($params['sort'] as $_k=>&$_v){
                if(!mAdv::updateData(['sort' => $_v], ['id' => $_k])){
                    return false;
                }
            }
            return true;
        });

        if($result){
            return response()->json([
                'status' => true,
                'message' => "操作成功",
            ]);
        }else{
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
    }

    public function sorts(Request $request,Content $content, $parentId = 0, $sonId = 0){
        return $content
            ->header('主题排序')
            ->breadcrumb(
                ['text' => '上级分类', 'url' => '/decoration/category/'.$parentId.'/edit/'.$sonId.'/edit/subject'],
                ['text' => '主题排序']
            )
            ->body(self::sortList($sonId));
    }

    public function sortList($sonId){
        $subject = mSubject::getAllByWhere(['status'=>1], ['id','name']);
        $subject = array_column($subject, 'name', 'id');

        $sql = 'select * from `hhz_decoration_adv` where FIND_IN_SET('.$sonId.',rela_id) and show_type = '.mAdv::SHOW_TYPE_1.' order by sort ASC';
        $data['list'] = mAdv::query($sql)->fetchAll();
        $data['list'] = array_map(function($_item)use($subject){
            $_item['subject'] = $subject[$_item['sid']];
            return $_item;
        }, $data['list']);
        $data['total'] = count($data['list']);
        $gridModel = new pGridDataModel($data['list'], $data['total'], [
            'perPage' => self::PAGE_SIZE
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableTools();
            $grid->disableCreateButton();
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableActions();

            $grid->tools(function (Grid\Tools $tool) {
                $tool->append(new UserButton(UserButton::TYPE_HREF, '', '主题位排序', '', '/admin/decoration/subject/sort'));
            });

            $grid->column('id', 'id')->sort();
            $grid->column('subject', '主题名称');
            $grid->column('sort', '权重');
            $grid->column('admin_id', '操作人')->display(function(){
                if(!$this->admin_id) {
                    return '暂无';
                }else{
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->column('edit_time', '编辑时间');

        });

        $list = $listGrid->render();

        return $list;
    }

}